<template>
  <form @submit="doOrder" report-submit>
  <div class="wrap wrap_buy" :class="{phone_x: iphonex}">
    <div class="mod_box_title">
      <div class="title">{{goods.goods_title}}</div>
      <div class="desc" v-if="goods.fee_purchase_note && goods.fee_purchase_note !== ''">
        <div v-html="goods.fee_purchase_note"></div>
      </div>
    </div>

    <div class="mod_box">
      <div class="mod_hd">
        <div class="title">使用日期</div>
      </div>
      <div class="mod_bd">
        <div class="mod_date_book">
          <div class="book_line">
            <div class="title" :class="{none: !currentPeriod.dayName}" @click="showMonthCalendar">{{currentPeriod.dayName}}
              <text v-if="isPintuan || isYuyue"> {{currentPeriod.dayData.starttime}}-{{currentPeriod.dayData.endtime}} </text>
            </div>
            <div class="title" :class="{none: !!currentPeriod.dayName}" @click="showMonthCalendar">请选择日期</div>
            <div class="desc" :class="{none: !currentPeriod.dayName}" v-if="isPintuan">
              <template v-if="currentPeriod.dayData.storage">
                充足
              </template>
              <template v-else>
                {{currentPeriod.dayData.remain}}张余票
              </template>
            </div>
            <div class="action" @click="showMonthCalendar">
              <text v-if="!currentPeriod.dayName">选择日期</text><text v-else>更改日期</text>
              <div class="iconfont icon-zsinto"></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="mod_box" :class="{none: isPintuan || isZuhe}">
      <div class="mod_hd">
        <div class="title">产品类型</div>
      </div>
      <div class="mod_bd">
        <div class="mod_text_tabs">
          <div v-for="item in goods.priceList"
              :class="{current: selTicketType.ticket_type === item.ticket_type}"
              :key="item.ticket_type" class="tab_item"
              @click="setTicketType(item)">{{item.ticketName}}<div class="iconfont icon-zssuccess"></div></div>
        </div>
      </div>
    </div>

    <div class="mod_box">
      <div class="mod_hd">
        <div class="title">游客信息</div>
      </div>
      <div class="mod_bd">
        <div class="mod_text_tabs">
          <div class="tab_item"
                v-for="item in goods.visitors"
                :class="{current: !!item._choose}"
                :key="item.v_id"
                @click="setVisitors(item)">{{item.v_truename}}<div class="iconfont icon-zssuccess"></div></div>
        </div>
        <div class="mod_form mod_form_people">

          <div class="form_block form_block_yk" v-for="(item, index) in selVisitors_info"
                :key="item.v_id_card">
            <div class="form_title">
              <div class="title">游客{{index + 1}}</div>
              <div class="action">
                <div class="btn_del" @click="setVisitors(item, true)">
                  <div class="iconfont icon-zsdelete"></div>
                </div>
              </div>
            </div>
            <div class="form_line">
              <div class="label">姓名</div>
              <div class="inp_text">{{item.v_truename}}</div>
            </div>
            <div class="form_line">
              <div class="label">身份证</div>
              <div class="inp_text">{{item.v_id_card}}</div>
            </div>
          </div>

          <div class="form_block form_block_yk" v-for="(item, index) in newVisitors"
                :key="item.time">
            <div class="form_title">
              <div class="title">游客{{index + selVisitors_info.length + 1}}</div>
              <div class="action">
                <div class="btn_del" @click="delVisitor(item, index)">
                  <div class="iconfont icon-zsdelete"></div>
                </div>
              </div>
            </div>
            <div class="form_line">
              <div class="label">姓名</div>
              <input type="text" placeholder-class="phcolor" v-model="item.name" class="inp_text" placeholder="请填写真实姓名" />
            </div>
            <div class="form_line">
              <div class="label">身份证
                <!-- <i class="iconfont icon-zsunfold"></i> -->
              </div>
              <input type="text" placeholder-class="phcolor" v-model="item.card" class="inp_text" placeholder="请填写证件号码" />
            </div>
          </div>
          <div class="form_btns">
            <div class="btn_add_line" @click="doAddVisitor">
              <i class="iconfont icon-zsaddone"></i>新增游客
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="mod_box">
      <div class="mod_hd">
        <div class="title">联系人</div>
      </div>
      <div class="mod_bd">
        <div class="mod_form mod_form_people">
          <div class="form_block">
            <!-- <div class="form_line">
              <div class="label">姓名</div>
              <input type="text" placeholder-class="phcolor"  v-model="contact.name" class="inp_text" placeholder="请填写真实姓名" />
            </div> -->
            <div class="form_line">
              <div class="label">手机号</div>
              <input type="text" placeholder-class="phcolor"  v-model="contact.tel" class="inp_text" placeholder="请填写手机号" />
            </div>
            <!-- <div class="form_line">
              <div class="label">身份证</div>
              <input type="text" placeholder-class="phcolor"  v-model="contact.card" class="inp_text" placeholder="请填写身份证号" />
            </div> -->
          </div>
        </div>
      </div>
    </div>

    <div class="mod_box" v-if="goods.is_appointment != 1">
      <div class="mod_hd">
        <div class="title">使用优惠</div>
      </div>
      <div class="mod_bd">
        <div class="mod_form mod_form_coupon">
          <div class="form_block" :class="{none: !goods.coupon || goods.coupon.length === 0}">
            <div class="form_line"
                  v-for="(item, index) in goods.coupon"
                  :key="item.code_id"
                  :class="{none: index !== 0}"
                  @click="chooseCoupon(item)">
              <div class="label">优惠券</div>
              <div class="form_content">
                {{item.name}}
                <span class="hl price">-&yen;{{item.face_value}}</span>
                <!-- <i class="iconfont icon-zsinto"></i> -->
              </div>
            </div>
          </div>
          <div class="form_block" :class="{none: goods.coupon && goods.coupon.length !== 0}">
            <div class="form_line">
              <div class="label">优惠券</div>
              <div class="form_content">暂无优惠券</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="mod_fixed_btn">
      <div class="price" v-if=" goods.is_appointment != 1">
        &yen;{{priceData.total}}
      </div>
      <div class="price_desc" v-if=" goods.is_appointment != 1">
        &yen;{{priceData.price}}x{{priceData.count}} <text v-if="priceData.discount">优惠券-&yen;{{priceData.discount}}</text>
      </div>
      <div class="ticket_total" v-if=" goods.is_appointment == 1">
        合计：{{selVisitors_info.length + newVisitors.length}} 张
      </div>
      <!--<div class="btn_buy" :class="{disabled: !buyBtnStatus}" @click="doOrder">{{goods.is_appointment == 1? '开始预约' : '确认支付'}}</div>-->
      <button formType="submit" class="btn_buy" :class="{disabled: !buyBtnStatus}">{{goods.is_appointment == 1? '开始预约' : '确认支付'}}</button>
    </div>

    <div class="mod_mask_layer" :class="{none: !showMark}" @click="clickMark" catchtouchmove="moveMask"></div>
    <div class="mod_calendar" :class="{none: !isShowMonthCalendar}">
      <div class="mod_calendar_header">
        <div class="cal_month_prev"
              :class="{disabled: monthCalendar.currentMonthIndex === 1}"
              @click="setCalendarM(1)">
          <div class="iconfont icon-zsback"></div>
        </div>
        <div class="calendar_month">{{monthCalendar.currentMonth.name}}</div>
        <div class="cal_month_next"
              :class="{disabled: monthCalendar.currentMonthIndex === 2 || monthCalendar.mLength === 1}"
              @click="setCalendarM(2)">
          <div class="iconfont icon-zsinto"></div>
        </div>
      </div>
      <div class="mod_calendar_body">
        <div class="cal_labels">
          <div class="cal_label">日</div>
          <div class="cal_label">一</div>
          <div class="cal_label">二</div>
          <div class="cal_label">三</div>
          <div class="cal_label">四</div>
          <div class="cal_label">五</div>
          <div class="cal_label">六</div>
        </div>
        <div class="cal_days">
          <div class="cal_day"
              v-for="item in monthCalendar.currentMonth.days"
              :key="item.key"
              :class="{cal_disabled: !item.active}"
              @click="monthDayClick(item)">
              {{item.day}}
            <div v-if="item.active" class="cal_info" :class="{'show' : isPintuan}">
              <template v-if="item.storage">
                充足
              </template>
              <template v-else>
                {{item.remain}}<br>余票
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="mod_tickets_picker" :class="{none: !isShowDayCalendar}" catchtouchmove="moveMask">
      <div class="picker_inner">
        <div class="picker_title">{{dayCalendar.dayName}}</div>
        <div class="picker_close" @click="hideDayCalendar">
          <div class="iconfont icon-zsclose"></div>
        </div>
          <div class="picker_content" :class="{none: dayCalendar.sDay.length === 0}">
            <div class="picker_label">上午</div>
            <div class="picker_item"
                  :class="{disabled: (item.remain === 0 || item._endtime < nowTime),
                            current: currentPeriod.dayName === dayCalendar.dayName && currentPeriod.dayData.starttime === item.starttime && currentPeriod.dayData.endtime === item.endtime}"
                  v-for="item in dayCalendar.sDay"
                  :key="item._starttime"
                  @click="dayTimeClick(item)">
              <div class="text">{{item.starttime}}-{{item.endtime}}</div>
              <div class="desc">
                <template v-if="item.storage">
                  充足
                </template>
                <template v-else>
                  {{item.remain}}张余票
                </template>
              </div>
              <div class="iconfont icon-zssuccess"></div>
            </div>
          </div>
          <div class="picker_content" :class="{none: dayCalendar.xDay.length === 0}">
            <div class="picker_label">下午</div>
            <div class="picker_item"
                  :class="{disabled: (item.remain === 0 || item._endtime < nowTime),
                            current: currentPeriod.dayName === dayCalendar.dayName && currentPeriod.dayData.starttime === item.starttime && currentPeriod.dayData.endtime === item.endtime}"
                  v-for="item in dayCalendar.xDay"
                  :key="item._starttime"
                  @click="dayTimeClick(item)">
              <div class="text">{{item.starttime}}-{{item.endtime}}</div>
              <div class="desc">
              <template v-if="item.storage">
                充足
              </template>
              <template v-else-if="item.remain === 0">
                已约满
              </template>
              <template v-else>
                {{item.remain}}张余票
              </template>
              </div>
              <div class="iconfont icon-zssuccess"></div>
            </div>
          </div>

          <div class="picker_btns">
            <div class="btn_ok" @click="closeDayCalendar">确定</div>
          </div>
      </div>
    </div>

    <div class="pop_modal" :class="{none: !showDeletePop}" catchtouchmove="moveMask">
      <div class="pop_modal_inner">
        <div class="modal_title">确定删除该游客？</div>
        <div class="modal_btns">
          <div class="btn_normal" @click="closeDeletePop">取消</div>
          <div class="btn_em" @click="confirmDeletePop">确定</div>
        </div>
      </div>
    </div>

    <div class="pop_modal" :class="{none: !showDeletePop2}">
      <div class="pop_modal_inner">
        <div class="modal_title">确定删除该游客？</div>
        <div class="modal_btns">
          <div class="btn_normal" @click="closeDeletePop2">取消</div>
          <div class="btn_em" @click="confirmDeletePop2">确定</div>
        </div>
      </div>
    </div>

  </div>
  </form>
</template>

<script>
import fly from '@/utils/fly'
import { getOpenid } from '@/utils/login'
import { addVisitor, asyncForEach, checkID, TicketType, doPay } from '@/utils/order'
import { mGetDate } from '@/utils/index'
import { reportData } from '@/utils/report'

export default {
  data () {
    let _nowTime = +new Date()
    return {
      goodsId: '',
      goods: {},
      newVisitors: [],
      selVisitors: [],
      selVisitors_info: [],
      selTicketType: {},
      contact: {
        name: '',
        tel: '',
        card: ''
      },
      showMark: false,
      isShowMonthCalendar: false,
      isShowDayCalendar: false,
      monthCalendar: {
        month1: {},
        month2: {},
        mLength: 1,
        currentMonthIndex: 1,
        currentMonth: {
          name: '',
          days: []
        }
      },
      dayCalendar: {
        dayName: '',
        sDay: [],
        xDay: []
      },
      currentPeriod: {
        dayName: '',
        dayData: {}
      },
      priceData: {
        price: 0,
        count: 0,
        discount: 0,
        total: 0
      },
      currentCouponId: '',
      isTicket: false,
      isPintuan: false,
      isZuhe: false,
      isYuyue: false,
      iphonex: false,
      showDeletePop: false,
      showDeletePop2: false,
      deleteIndex: -1,
      deleteIndex2: {},
      nowTime: _nowTime,
      buyBtnStatus: true
    }
  },
  watch: {
    selTicketType () {
      this.calcPrice()
    },
    selVisitors () {
      this.calcPrice()
    },
    newVisitors () {
      this.calcPrice()
    }
  },
  methods: {
    getSystemInfo () {
      var that = this
      wx.getSystemInfo({
        success: function (res) {
          if (res.model.toLowerCase().indexOf('iphone x') > -1) {
            that.iphonex = true
          }
        }
      })
    },
    async doOrder (e) {
      // 检查是否选择时间
      if (!this.currentPeriod.dayName) {
        wx.showToast({
          title: '请选择日期',
          icon: 'none'
        })
        return
      }
      // 检查联系人是否填写
      if (!this.contact.tel) {
        wx.showToast({
          title: '请填写联系人姓名和手机号',
          icon: 'none'
        })
        return
      }
      // if (!this.contact.card || !checkID('' + this.contact.card)) {
      //   wx.showToast({
      //     title: '请正确填写联系人身份证号',
      //     icon: 'none'
      //   })
      //   return
      // }
      // 检查新增游客数据是否符合要求
      let arrVisitors = [].concat(this.selVisitors)
      if (this.newVisitors.length > 0) {
        let pass = true
        this.newVisitors.forEach(v => {
          if (!v.name || !v.card || !checkID('' + v.card)) {
            pass = false
          }
        })
        if (!pass) {
          wx.showToast({
            title: '请正确填写完整游客信息',
            icon: 'none'
          })
          return
        }
        let vid = await this.addVisitors()
        arrVisitors = arrVisitors.concat(vid)
      } else if (this.selVisitors.length === 0) { // 如果没有新增游客，则需判断是否选择游客
        wx.showToast({
          title: '请选择或填写游客信息',
          icon: 'none'
        })
        return
      }
      if (arrVisitors.length > 10) {
        wx.showToast({
          title: '单个订单不能超过10个游客',
          icon: 'none'
        })
        return
      }
      // 检查选择的时间是否正确
      // if (this.currentPeriod.dayData._starttime < +new Date()) {
      //   console.log('this.currentPeriod.dayData._starttime', this.currentPeriod.dayData._starttime, +new Date())
      //   wx.showToast({
      //     title: '所选门票时间小于当前时间',
      //     icon: 'none'
      //   })
      //   return
      // }
      // 检查余票是否充足
      if (!this.currentPeriod.dayData.storage && this.currentPeriod.dayData.remain < arrVisitors.length) {
        wx.showToast({
          title: '所选门票余票不足',
          icon: 'none'
        })
        return
      }

      this.buyBtnStatus = false

      wx.showLoading({
        title: '正在下单'
      })

      let openid = await getOpenid()
      let url = `Order/post?wx_openid=${openid}&goods_id=${this.goodsId}&contact_tel=${this.contact.tel}&ticket_type=${this.selTicketType.ticket_type}&quantity=${arrVisitors.length}&start_time=${this.currentPeriod.dayData._starttime}&end_time=${this.currentPeriod.dayData._endtime}&v_ids=${arrVisitors.join(',')}&code_id=${this.currentCouponId}&formId=${e.mp.detail.formId}`
      if (this.isPintuan) { // 拼团需要带上这个参数
        url += `&gtrg_id=${this.currentPeriod.dayData.gtrg_id}`
      }
      if (this.isYuyue) {
        url += `&span_time=${this.currentPeriod.dayData._index}`
      }
      let res = await fly.post(url)
      if (res && res.code === 200 && res.data && (res.data.order_sn)) {
        wx.hideLoading()
        if (this.isYuyue) {
          wx.redirectTo({
            url: '/pages/order-detail/main?id=' + res.data.order_sn
          })
        } else {
          let wxPayRes = await doPay(res.data.order_sn)
          if (wxPayRes && wxPayRes.code === 200) {
            reportData({
              funcx: '交易流程-' + (this.isPintuan ? '拼团成功' : '购买成功'),
              keyx: this.goodsId
            })
            wx.redirectTo({
              url: '/pages/order-detail/main?id=' + res.data.order_sn
            })
          } else {
            reportData({
              funcx: '交易流程-' + (this.isPintuan ? '拼团失败' : '购买失败'),
              keyx: this.goodsId
            })
            wx.redirectTo({
              url: '/pages/order-detail/main?id=' + res.data.order_sn
            })
          }
        }
      } else {
        wx.hideLoading()
        reportData({
          funcx: '交易流程-' + (this.isPintuan ? '拼团失败' : '购买失败') + '-' + (res.code || ''),
          keyx: this.goodsId
        })
        wx.showToast({
          title: `${res ? (res.msg + '(' + res.code + ')') : ''}`,
          icon: 'none'
        })
        this.buyBtnStatus = true
      }
    },
    async addVisitors () {
      const start = async () => {
        let vid = []
        await asyncForEach(this.newVisitors, async (v) => {
          let res = await addVisitor({
            name: v.name,
            type: 1,
            card: v.card
          })
          if (res && res.code === 200 && res.data) {
            vid.push(res.data)
          }
        })
        return vid
      }
      let res = await start()
      return res
    },
    setTicketType (item) {
      this.selTicketType = item
    },
    setVisitors (item, showPop) {
      if (showPop) {
        this.showDeletePop2 = true
        this.deleteIndex2 = item
        return
      }
      if (this.selVisitors.indexOf(item.v_id) > -1) {
        let i = this.selVisitors.indexOf(item.v_id)
        this.selVisitors.splice(i, 1)
        this.selVisitors_info.splice(i, 1)
      } else {
        this.selVisitors.push(item.v_id)
        this.selVisitors_info.push(item)
      }
      item._choose = !item._choose
    },
    doAddVisitor () {
      this.newVisitors.push({
        name: '',
        time: +new Date(),
        card: ''
      })
    },
    delVisitor (item, index) {
      this.showDeletePop = true
      this.deleteIndex = index
    },
    confirmDeletePop () {
      this.newVisitors.splice(this.deleteIndex, 1)
      this.showDeletePop = false
    },
    confirmDeletePop2 () {
      this.setVisitors(this.deleteIndex2)
      this.showDeletePop2 = false
    },
    async getMonthTicket () {
      let res
      if (this.isPintuan) {
        res = this.calcGroupMonth()
      } else if (this.isYuyue) {
        res = await fly.post(`Ticket/yyStock`)
        console.log('--', res)
      } else {
        res = await fly.post(`Ticket/queryMonth?goods_id=${this.goodsId}`)
      }
      if (res && res.code === 200 && res.data) {
        // 这里有29天，可能渲染出一个月，也可能是两个月的数据
        let first
        let firstDay
        let second
        let fstMonth = []
        let secMonth = []
        Object.keys(res.data).forEach(key => {
          let item = res.data[key]
          let dd = key.split('-').map(ii => +ii)
          let rDay = new Date(dd[0], dd[1] - 1, dd[2])
          let r = {
            key: +rDay,
            active: true,
            day: rDay.getDate(),
            _day: key,
            remain: item.remain,
            storage: item.storage === -1
          }
          if (this.isYuyue) {
            r.yyTimes = item
          }
          if (!first) {
            first = rDay
            firstDay = r
          }
          if (first.getMonth() === rDay.getMonth()) {
            fstMonth.push(r)
          } else {
            if (!second) {
              second = rDay
            }
            secMonth.push(r)
          }
        })
        // 组装第一个月数据
        this.monthCalendar.month1 = this.calcMonthData(first, fstMonth)
        // 如果有第二个月
        if (second) {
          this.monthCalendar.mLength = 2
          this.monthCalendar.month2 = this.calcMonthData(second, secMonth)
        }
        return firstDay
      } else {
        wx.showToast({
          title: `月票务信息异常${res ? ('(' + res.code + ')') : ''}`,
          icon: 'none'
        })
      }
    },
    calcMonthData (day, monthData) { // 根据指定日组装该月数据
      let year = day.getFullYear()
      let month = day.getMonth() + 1
      let dates = mGetDate(year, month)
      let nowDate = new Date()
      let arrDates = [...Array(dates)].map((_, i) => {
        return {
          key: `${month}blank${i}`,
          active: false,
          day: (i + 1 === nowDate.getDate() && month === nowDate.getMonth() + 1) ? '今天' : i + 1
        }
      })
      // 此处的问题，查询余票后日期添加的位置有问题
      // arrDates.splice(day.getDate() - 1, monthData.length, ...monthData)
      monthData.forEach(item => {
        arrDates.splice(item.day - 1, 1, item)
      })
      let fst = new Date(year, day.getMonth(), 1)
      let days = [...Array(fst.getDay())].map((_, i) => {
        return {
          key: `${month}empty${i}`,
          active: false
        }
      }).concat(arrDates)
      nowDate = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate())
      days.forEach(item => {
        if (item.key === +nowDate) {
          item.day = '今天'
        }
      })

      return {
        name: `${year}年${month}月`,
        days
      }
    },
    setCalendarM (i) {
      this.monthCalendar.currentMonthIndex = i
      this.monthCalendar.currentMonth = this.monthCalendar['month' + i]
      if (this.goodsId === '441' || this.goodsId === '454') {
        if (this.monthCalendar.currentMonth.name === '2019年9月') {
          this.monthCalendar.currentMonth.days[12].active = false
          this.monthCalendar.currentMonth.days[13].active = false
          this.monthCalendar.currentMonth.days[14].active = false
          this.monthCalendar.currentMonth.days[20].active = false
          this.monthCalendar.currentMonth.days[21].active = false
        }
      }
      if (this.goodsId === '477' || this.goodsId === '476') {
        if (this.monthCalendar.currentMonth.name === '2019年9月') {
          this.monthCalendar.currentMonth.days[9].active = false
          this.monthCalendar.currentMonth.days[10].active = false
          this.monthCalendar.currentMonth.days[11].active = false

          this.monthCalendar.currentMonth.days.map(x => {
            if (x.day > 15) {
              x.active = false
              return x
            }
          })
        }
        if (this.monthCalendar.currentMonth.name === '2019年10月') {
          this.monthCalendar.currentMonth.days.map(x => {
            x.active = false
            return x
          })
        }
      }
    },
    showMonthCalendar () {
      this.isShowMonthCalendar = true
      this.showMark = true
    },
    hideDayCalendar () {
      this.isShowDayCalendar = false
    },
    clickMark () {
      this.showMark = false
      this.isShowMonthCalendar = false
      this.isShowDayCalendar = false
    },
    moveMask () {

    },
    async getDayTicket (day) {
      let res
      if (this.isPintuan) {
        res = this.calcGroupDay(day)
      } else {
        res = await fly.post(`Ticket/queryDay?goods_id=${this.goodsId}&date=${day}`)
      }
      if (res && res.code === 200 && res.data) {
        this.dayCalendar.dayName = day
        let sDay = []
        let xDay = []
        res.data.forEach(item => {
          let dd = day.split('-').map(ii => +ii)
          let sst = item.starttime.split(':').map(ii => +ii)
          let eet = item.endtime.split(':').map(ii => +ii)
          // item._starttime = +new Date(`${day} ${item.starttime}:00`)
          item._starttime = +new Date(dd[0], dd[1] - 1, dd[2], sst[0], sst[1], 0)
          // item._endtime = +new Date(`${day} ${item.endtime}:00`)
          item._endtime = +new Date(dd[0], dd[1] - 1, dd[2], eet[0], eet[1], 0)
          item.storage = item.storage === -1
          if (item.starttime < '12:00') {
            sDay.push(item)
          } else {
            xDay.push(item)
          }
        })
        this.dayCalendar.sDay = sDay
        this.dayCalendar.xDay = xDay
        return res.data
      } else {
        wx.showToast({
          title: `日票务信息异常${res ? ('(' + res.code + ')') : ''}`,
          icon: 'none'
        })
      }
    },
    async monthDayClick (item) {
      if (!item.active) {
        return
      }
      let dayData = []
      if (this.isYuyue) {
        dayData = [1]
        let timeTabel = [
          ['08:30', '10:30'],
          ['10:30', '12:30'],
          ['12:30', '14:30'],
          ['14:30', '16:30'],
          ['16:30', '17:00']
        ]

        this.dayCalendar.dayName = item._day
        let sDay = []
        let xDay = []
        item.yyTimes.forEach((item, index) => {
          let it = {}
          it.starttime = timeTabel[index][0]
          it.endtime = timeTabel[index][1]
          it._starttime = +new Date(`${this.dayCalendar.dayName.replace(/-/g, '/')} ${timeTabel[index][0]}:00`)
          it._endtime = +new Date(`${this.dayCalendar.dayName.replace(/-/g, '/')} ${timeTabel[index][1]}:00`)
          it.storage = item === -1
          it.remain = item
          it._index = index
          if (index < 2) {
            sDay.push(it)
          } else {
            xDay.push(it)
          }
        })
        this.dayCalendar.sDay = sDay
        this.dayCalendar.xDay = xDay
        dayData = item
      } else {
        dayData = await this.getDayTicket(item._day)
      }
      if (dayData.length === 1) {
        this.dayTimeClick(dayData[0])
      } else {
        this.isShowDayCalendar = true
      }
      this.isShowMonthCalendar = false
      this.showMark = false
    },
    closeDayCalendar () {
      this.isShowDayCalendar = false
    },
    dayTimeClick (item) {
      this.currentPeriod.dayName = this.dayCalendar.dayName
      this.currentPeriod.dayData = item
      this.closeDayCalendar()
    },
    calcPrice () {
      let price = this.selTicketType.price || 0
      let count = this.selVisitors.length + this.newVisitors.length
      this.priceData.price = price
      this.priceData.count = count
      this.priceData.total = price * count - this.priceData.discount
      if (this.priceData.total < 0) {
        this.priceData.total = 0
      }
    },
    chooseCoupon (item) {
      this.currentCouponId = item.code_id
      this.priceData.discount = item.face_value
    },
    calcGroupMonth () {
      let map = {}
      let max = this.goods.max
      this.goods.group.forEach(item => {
        let t = new Date(item.start_time * 1000)
        let d = `${t.getFullYear()}-${('0' + (t.getMonth() + 1)).slice(-2)}-${('0' + t.getDate()).slice(-2)}`
        let remain = max - item.already
        item.remain = remain
        item.storage = 1
        item.starttime = `${('0' + t.getHours()).slice(-2)}:${('0' + t.getMinutes()).slice(-2)}`
        let et = new Date(item.end_time * 1000)
        item.endtime = `${('0' + et.getHours()).slice(-2)}:${('0' + et.getMinutes()).slice(-2)}`
        if (map[d]) {
          map[d].remain += remain
          map[d]._data.push(item)
        } else {
          map[d] = {
            remain: remain,
            storage: 1,
            _data: [item]
          }
        }
      })
      this.goods._group = map
      return {
        code: 200,
        data: map
      }
    },
    calcGroupDay (day) {
      return {
        code: 200,
        data: this.goods._group[day]._data
      }
    },
    closeDeletePop () {
      this.showDeletePop = false
    },
    closeDeletePop2 () {
      this.showDeletePop2 = false
    }
  },
  async onLoad () {
    this.currentPeriod = {
      dayName: '',
      dayData: {}
    }
    this.selVisitors = []
    this.selVisitors_info = []
    this.newVisitors = []

    const {
      id
    } = this.$root.$mp.query
    this.goodsId = id

    reportData({
      funcx: '交易流程-信息填写',
      keyx: this.goodsId
    })

    this.getSystemInfo()

    let openid = await getOpenid()
    let res = await fly.post(`Order/index?wx_openid=${openid}&goods_id=${this.goodsId}`)
    if (res && res.code === 200 && res.data) {
      this.isPintuan = res.data.is_group === 1
      this.isYuyue = res.data.is_appointment === 1
      // 拼团场景整合下价格信息
      if (this.isPintuan) {
        let p = res.data.priceList
        p.ticket_type = '111'
        res.data.priceList = [p]
      }

      res.data.priceList.forEach(item => {
        item.ticketName = TicketType[item.ticket_type]
      })
      this.selTicketType = res.data.priceList[0]

      this.isZuhe = this.selTicketType.ticket_type === 99

      this.goods = res.data

      // 重制日期为空
      this.monthCalendar = {
        month1: {},
        month2: {},
        mLength: 1,
        currentMonthIndex: 1,
        currentMonth: {
          name: '',
          days: []
        }
      }

      console.log('this.goods.coupon', this.goods.coupon)
      if (this.goods.coupon && this.goods.coupon.length) {
        this.chooseCoupon(this.goods.coupon[0])
      }

      // 获取票务信息
      // let firstDay = await this.getMonthTicket()
      await this.getMonthTicket()
      this.setCalendarM(1)
      // 获取第一天的票务信息
      // let dayData = await this.getDayTicket(firstDay._day)
      // this.dayTimeClick(dayData[0])
    } else {
      reportData({
        funcx: '交易流程-下订单异常-' + (res.code || ''),
        keyx: this.goodsId
      })
      wx.showToast({
        title: `下订单异常${res ? ('(' + res.code + ')') : ''}`,
        icon: 'none'
      })
    }
  },
  onShow () {
    this.nowTime = +new Date()
    this.buyBtnStatus = true
  }
}
</script>

<style lang="scss">
@import "buy.scss";
</style>
